#!/bin/bash

set -euo pipefail

project_root_dir="$(cd "$(dirname "$0")/.." && pwd -P)"
work_dir="/workplace/aws-node-termination-handler"
container_name="nth_unit_test_on_linux"
deps="go,git,make"
recreate=0
usage=$(cat <<EOM
  usage: run-unit-tests-in-docker [-c CONTAINER_NAME] [-d DEP1,...] [-r]

    Runs "make unit-test" in an Alpine Linux docker container.

    Creates and initializes a new container if one does not already exist.

    Options:
      -c     Container name (default "$container_name")
      -d     Linux dependencies to install (default "$deps")
      -r     Recreate container

EOM
)

while getopts "c:d:r" opt; do
  case "$opt" in
    c) container_name="$OPTARG"
       ;;

    d) deps="$deps,$OPTARG"
       ;;

    r) recreate=1
       ;;

    *) echo "$usage" 1>&2
       exit
       ;;
  esac
done

echo "unit tests will be run in docker container named $container_name"

if [[ $recreate -eq 1 ]]; then
  docker container rm "$container_name" >/dev/null 2>&1 || true
fi

if ! [[ -n $(docker container ls -a | grep "$container_name") ]]; then
  echo "creating container ..."

  IFS=',' read -ra deps <<< "$deps"
  echo "dependencies to install: ${deps[*]}"

  docker container create \
      --name "$container_name" \
      --volume "$project_root_dir:$work_dir" \
      --env GOPROXY=direct \
      --env GO111MODULE=auto \
      --workdir "$work_dir" \
      --init \
      alpine:latest \
      sh -c "apk add ${deps[*]} && make clean unit-test"

  echo "container created"
else
  echo "container exists"
fi

echo "running unit tests ..."
docker container start --attach "$container_name"

